package com.yy.json;

public class FieldSerializer {
    private FieldInfo mFieldInfo;
    private String key;
    private boolean isPrimitive;
    private Class<?> type;

    public FieldSerializer(FieldInfo fieldInfo) {
        mFieldInfo = fieldInfo;
        this.key = '"' + fieldInfo.name + "\":";
        type = fieldInfo.type;
        //基本类型或包装类型
        isPrimitive = Utils.isBox(type) || type.isPrimitive();
    }

    public String serializer(JsonConfig config, Object object) {
        Object value = mFieldInfo.get(object);
        if (value == null) {
            return "";
        }
        StringBuilder builder = new StringBuilder();
        if (isPrimitive) {
            builder.append(key);
            builder.append(value);
        } else if (Utils.isString(type)) {
            builder.append(key);
            builder.append("\"");
            builder.append(value);
            builder.append("\"");
        } else {
            ObjectSerializer serializer = config.getSerializer(mFieldInfo.type);
            builder.append(key);
            serializer.serializer(config, builder, value);
        }
        return builder.toString();
    }
}
